import React, { useState, useCallback } from 'react';
import {
  Card,
  Button,
  Space,
  Input,
  Select,
  Divider,
  Row,
  Col,
  Tag,
  Rate,
  Progress,
  Alert,
  Table,
  Tabs,
  message,
  Spin,
  Badge,
  Tooltip,
  Modal,
  Form,
  Slider,
  Switch,
  Statistic
} from 'antd';
import {
  PlayCircleOutlined,
  ExperimentOutlined,
  BarChartOutlined,
  SyncOutlined,
  SaveOutlined,
  ClearOutlined,
  CopyOutlined,
  ThunderboltOutlined,
  RobotOutlined,
  BulbOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { PromptTemplate } from '@/types/prompt';
import './style.css';

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

interface TestCase {
  id: string;
  input: string;
  expectedOutput?: string;
  actualOutput?: string;
  score?: number;
  metrics?: TestMetrics;
  status: 'pending' | 'running' | 'success' | 'failed';
  createdAt: Date;
}

interface TestMetrics {
  relevance: number;      // 相关性
  coherence: number;      // 连贯性
  creativity: number;     // 创造性
  accuracy: number;       // 准确性
  completeness: number;   // 完整性
  responseTime: number;   // 响应时间(ms)
}

interface ABTestResult {
  promptA: PromptTemplate;
  promptB: PromptTemplate;
  winner?: 'A' | 'B' | 'tie';
  testCases: TestCase[];
  comparison: {
    metric: string;
    scoreA: number;
    scoreB: number;
    difference: number;
  }[];
}

interface PromptTesterProps {
  prompt?: PromptTemplate;
  onTest?: (prompt: PromptTemplate, input: string) => Promise<string>;
  onBatchTest?: (prompt: PromptTemplate, inputs: string[]) => Promise<string[]>;
  onABTest?: (promptA: PromptTemplate, promptB: PromptTemplate, input: string) => Promise<ABTestResult>;
  onSaveResults?: (results: TestCase[]) => void;
  className?: string;
}

const PromptTester: React.FC<PromptTesterProps> = ({
  prompt,
  onTest,
  onBatchTest,
  onABTest,
  onSaveResults,
  className = ''
}) => {
  const [testInput, setTestInput] = useState('');
  const [testOutput, setTestOutput] = useState('');
  const [testCases, setTestCases] = useState<TestCase[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('single');
  const [batchInputs, setBatchInputs] = useState<string[]>(['']);
  const [abTestPromptB, setABTestPromptB] = useState<PromptTemplate | null>(null);
  const [abTestResult, setABTestResult] = useState<ABTestResult | null>(null);
  const [showMetricsModal, setShowMetricsModal] = useState(false);
  const [selectedTestCase, setSelectedTestCase] = useState<TestCase | null>(null);
  const [autoScore, setAutoScore] = useState(true);

  // 单个测试
  const handleSingleTest = useCallback(async () => {
    if (!prompt || !onTest || !testInput) {
      message.warning('请输入测试内容');
      return;
    }

    setLoading(true);
    try {
      const output = await onTest(prompt, testInput);
      setTestOutput(output);
      
      // 创建测试用例
      const testCase: TestCase = {
        id: Date.now().toString(),
        input: testInput,
        actualOutput: output,
        status: 'success',
        createdAt: new Date(),
        metrics: autoScore ? generateMetrics(output) : undefined,
        score: autoScore ? calculateOverallScore(generateMetrics(output)) : undefined
      };
      
      setTestCases([testCase, ...testCases]);
      message.success('测试完成');
    } catch (error) {
      message.error('测试失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [prompt, onTest, testInput, testCases, autoScore]);

  // 批量测试
  const handleBatchTest = useCallback(async () => {
    if (!prompt || !onBatchTest) {
      message.warning('批量测试功能未配置');
      return;
    }

    const validInputs = batchInputs.filter(input => input.trim());
    if (validInputs.length === 0) {
      message.warning('请输入测试内容');
      return;
    }

    setLoading(true);
    try {
      const outputs = await onBatchTest(prompt, validInputs);
      const newTestCases = validInputs.map((input, index) => ({
        id: `${Date.now()}_${index}`,
        input,
        actualOutput: outputs[index],
        status: 'success' as const,
        createdAt: new Date(),
        metrics: autoScore ? generateMetrics(outputs[index]) : undefined,
        score: autoScore ? calculateOverallScore(generateMetrics(outputs[index])) : undefined
      }));
      
      setTestCases([...newTestCases, ...testCases]);
      message.success(`批量测试完成，共 ${validInputs.length} 个用例`);
    } catch (error) {
      message.error('批量测试失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [prompt, onBatchTest, batchInputs, testCases, autoScore]);

  // A/B测试
  const handleABTest = useCallback(async () => {
    if (!prompt || !abTestPromptB || !onABTest || !testInput) {
      message.warning('请配置完整的A/B测试参数');
      return;
    }

    setLoading(true);
    try {
      const result = await onABTest(prompt, abTestPromptB, testInput);
      setABTestResult(result);
      message.success('A/B测试完成');
    } catch (error) {
      message.error('A/B测试失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [prompt, abTestPromptB, onABTest, testInput]);

  // 生成测试指标（使用真实API或基础评估）
  const generateMetrics = (output: string): TestMetrics => {
    // TODO: 调用实际的评估API服务
    // 目前使用基础的文本分析作为替代
    const wordCount = output.split(/\s+/).length;
    const sentences = output.split(/[.!?]+/).length;
    const avgWordsPerSentence = wordCount / sentences;
    
    return {
      relevance: Math.min(90, Math.max(60, wordCount * 2)), // 基于字数的相关性评估
      coherence: Math.min(95, Math.max(50, avgWordsPerSentence * 8)), // 基于句子长度的连贯性
      creativity: Math.min(85, Math.max(40, output.length * 0.1)), // 基于内容长度的创造性
      accuracy: Math.min(90, Math.max(70, 85)), // 默认准确性分数
      completeness: Math.min(95, Math.max(60, wordCount * 3)), // 基于字数的完整性
      responseTime: 1500 + Math.random() * 2000 // 模拟响应时间 1.5-3.5秒
    };
  };

  // 计算总分
  const calculateOverallScore = (metrics?: TestMetrics): number => {
    if (!metrics) return 0;
    const weights = {
      relevance: 0.25,
      coherence: 0.2,
      creativity: 0.15,
      accuracy: 0.25,
      completeness: 0.15
    };
    
    return Object.entries(weights).reduce((score, [key, weight]) => {
      return score + (metrics[key as keyof typeof weights] || 0) * weight;
    }, 0);
  };

  // 保存测试结果
  const handleSaveResults = useCallback(() => {
    if (onSaveResults && testCases.length > 0) {
      onSaveResults(testCases);
      message.success('测试结果已保存');
    }
  }, [onSaveResults, testCases]);

  // 清空测试结果
  const handleClearResults = useCallback(() => {
    Modal.confirm({
      title: '清空测试结果',
      content: '确定要清空所有测试结果吗？',
      onOk: () => {
        setTestCases([]);
        setTestOutput('');
        setABTestResult(null);
        message.info('测试结果已清空');
      }
    });
  }, []);

  // 复制输出
  const handleCopyOutput = useCallback((text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('已复制到剪贴板');
    });
  }, []);

  // 渲染测试指标
  const renderMetrics = (metrics: TestMetrics) => (
    <Space direction="vertical" style={{ width: '100%' }}>
      <div className="metric-item">
        <span>相关性</span>
        <Progress percent={metrics.relevance} size="small" />
      </div>
      <div className="metric-item">
        <span>连贯性</span>
        <Progress percent={metrics.coherence} size="small" />
      </div>
      <div className="metric-item">
        <span>创造性</span>
        <Progress percent={metrics.creativity} size="small" />
      </div>
      <div className="metric-item">
        <span>准确性</span>
        <Progress percent={metrics.accuracy} size="small" />
      </div>
      <div className="metric-item">
        <span>完整性</span>
        <Progress percent={metrics.completeness} size="small" />
      </div>
      <div className="metric-item">
        <span>响应时间</span>
        <Tag color={metrics.responseTime < 1000 ? 'green' : metrics.responseTime < 3000 ? 'orange' : 'red'}>
          {metrics.responseTime.toFixed(0)}ms
        </Tag>
      </div>
    </Space>
  );

  // 测试用例表格列
  const testCaseColumns = [
    {
      title: '输入',
      dataIndex: 'input',
      key: 'input',
      width: '30%',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      )
    },
    {
      title: '输出',
      dataIndex: 'actualOutput',
      key: 'actualOutput',
      width: '30%',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      )
    },
    {
      title: '评分',
      dataIndex: 'score',
      key: 'score',
      width: '15%',
      render: (score: number) => score ? (
        <div>
          <Rate value={score / 20} disabled allowHalf />
          <span style={{ marginLeft: 8, fontSize: 12 }}>{score.toFixed(1)}</span>
        </div>
      ) : '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      render: (status: string) => {
        const statusConfig = {
          pending: { color: 'default', icon: <ClockCircleOutlined />, text: '待测' },
          running: { color: 'processing', icon: <SyncOutlined spin />, text: '测试中' },
          success: { color: 'success', icon: <CheckCircleOutlined />, text: '成功' },
          failed: { color: 'error', icon: <CloseCircleOutlined />, text: '失败' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: TestCase) => (
        <Space>
          {record.metrics && (
            <Button
              size="small"
              icon={<BarChartOutlined />}
              onClick={() => {
                setSelectedTestCase(record);
                setShowMetricsModal(true);
              }}
            >
              指标
            </Button>
          )}
          <Button
            size="small"
            icon={<CopyOutlined />}
            onClick={() => handleCopyOutput(record.actualOutput || '')}
          />
        </Space>
      )
    }
  ];

  return (
    <div className={`prompt-tester ${className}`}>
      <Card
        title={
          <Space>
            <ExperimentOutlined />
            <span>提示词测试器</span>
            {prompt && <Tag color="blue">{prompt.name}</Tag>}
          </Space>
        }
        extra={
          <Space>
            <Switch
              checkedChildren="自动评分"
              unCheckedChildren="手动评分"
              checked={autoScore}
              onChange={setAutoScore}
            />
            {testCases.length > 0 && (
              <>
                <Button icon={<SaveOutlined />} onClick={handleSaveResults}>
                  保存结果
                </Button>
                <Button icon={<ClearOutlined />} onClick={handleClearResults}>
                  清空结果
                </Button>
              </>
            )}
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <span>
                <ThunderboltOutlined />
                单个测试
              </span>
            }
            key="single"
          >
            <Space direction="vertical" style={{ width: '100%' }} size={16}>
              <div>
                <div style={{ marginBottom: 8 }}>测试输入：</div>
                <TextArea
                  value={testInput}
                  onChange={e => setTestInput(e.target.value)}
                  placeholder="请输入测试内容..."
                  rows={4}
                  showCount
                  maxLength={1000}
                />
              </div>
              
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleSingleTest}
                loading={loading}
                disabled={!prompt || !testInput}
                block
              >
                开始测试
              </Button>

              {testOutput && (
                <div>
                  <div style={{ marginBottom: 8 }}>
                    测试输出：
                    <Button
                      size="small"
                      icon={<CopyOutlined />}
                      onClick={() => handleCopyOutput(testOutput)}
                      style={{ marginLeft: 8 }}
                    >
                      复制
                    </Button>
                  </div>
                  <Card className="output-card">
                    <pre>{testOutput}</pre>
                  </Card>
                </div>
              )}
            </Space>
          </TabPane>

          <TabPane
            tab={
              <span>
                <BulbOutlined />
                批量测试
              </span>
            }
            key="batch"
          >
            <Space direction="vertical" style={{ width: '100%' }} size={16}>
              <Alert
                message="批量测试说明"
                description="输入多个测试用例，每行一个，系统将自动批量执行测试并生成报告。"
                type="info"
                showIcon
              />
              
              {batchInputs.map((input, index) => (
                <div key={index}>
                  <div style={{ marginBottom: 8 }}>测试用例 {index + 1}：</div>
                  <Input.Group compact>
                    <Input
                      style={{ width: 'calc(100% - 100px)' }}
                      value={input}
                      onChange={e => {
                        const newInputs = [...batchInputs];
                        newInputs[index] = e.target.value;
                        setBatchInputs(newInputs);
                      }}
                      placeholder="请输入测试内容..."
                    />
                    <Button
                      onClick={() => {
                        const newInputs = batchInputs.filter((_, i) => i !== index);
                        setBatchInputs(newInputs.length > 0 ? newInputs : ['']);
                      }}
                      danger
                    >
                      删除
                    </Button>
                  </Input.Group>
                </div>
              ))}
              
              <Button
                onClick={() => setBatchInputs([...batchInputs, ''])}
                style={{ width: '100%' }}
                dashed
              >
                + 添加测试用例
              </Button>
              
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleBatchTest}
                loading={loading}
                disabled={!prompt || batchInputs.every(i => !i.trim())}
                block
              >
                开始批量测试
              </Button>
            </Space>
          </TabPane>

          <TabPane
            tab={
              <span>
                <RobotOutlined />
                A/B测试
              </span>
            }
            key="ab"
            disabled={!onABTest}
          >
            <Space direction="vertical" style={{ width: '100%' }} size={16}>
              <Alert
                message="A/B测试说明"
                description="对比两个不同提示词的效果，帮助您选择最优方案。"
                type="info"
                showIcon
              />
              
              <Row gutter={16}>
                <Col span={12}>
                  <Card title="提示词 A" size="small">
                    {prompt ? (
                      <div>
                        <div className="ab-prompt-name">{prompt.name}</div>
                        <div className="ab-prompt-desc">{prompt.description}</div>
                      </div>
                    ) : (
                      <Empty description="请选择提示词 A" />
                    )}
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="提示词 B" size="small">
                    {abTestPromptB ? (
                      <div>
                        <div className="ab-prompt-name">{abTestPromptB.name}</div>
                        <div className="ab-prompt-desc">{abTestPromptB.description}</div>
                      </div>
                    ) : (
                      <Empty description="请选择提示词 B" />
                    )}
                  </Card>
                </Col>
              </Row>
              
              <div>
                <div style={{ marginBottom: 8 }}>测试输入：</div>
                <TextArea
                  value={testInput}
                  onChange={e => setTestInput(e.target.value)}
                  placeholder="请输入A/B测试内容..."
                  rows={3}
                />
              </div>
              
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleABTest}
                loading={loading}
                disabled={!prompt || !abTestPromptB || !testInput}
                block
              >
                开始A/B测试
              </Button>

              {abTestResult && (
                <Card title="A/B测试结果" size="small">
                  <Row gutter={16}>
                    <Col span={8}>
                      <Statistic
                        title="获胜方"
                        value={abTestResult.winner === 'A' ? '提示词 A' : abTestResult.winner === 'B' ? '提示词 B' : '平局'}
                        valueStyle={{ color: abTestResult.winner === 'A' ? '#52c41a' : abTestResult.winner === 'B' ? '#1890ff' : '#8c8c8c' }}
                      />
                    </Col>
                    {abTestResult.comparison.map((comp, index) => (
                      <Col span={8} key={index}>
                        <Statistic
                          title={comp.metric}
                          value={comp.difference}
                          precision={1}
                          valueStyle={{ color: comp.difference > 0 ? '#52c41a' : '#ff4d4f' }}
                          prefix={comp.difference > 0 ? '+' : ''}
                          suffix="%"
                        />
                      </Col>
                    ))}
                  </Row>
                </Card>
              )}
            </Space>
          </TabPane>
        </Tabs>

        {testCases.length > 0 && (
          <>
            <Divider />
            <div>
              <h4>测试历史 ({testCases.length})</h4>
              <Table
                dataSource={testCases}
                columns={testCaseColumns}
                rowKey="id"
                size="small"
                pagination={{ pageSize: 5 }}
              />
            </div>
          </>
        )}
      </Card>

      {/* 指标详情Modal */}
      <Modal
        title="测试指标详情"
        open={showMetricsModal}
        onCancel={() => {
          setShowMetricsModal(false);
          setSelectedTestCase(null);
        }}
        footer={null}
        width={600}
      >
        {selectedTestCase?.metrics && renderMetrics(selectedTestCase.metrics)}
      </Modal>
    </div>
  );
};

export default PromptTester;